import axios from 'axios';
import router from '@/router';

const config = {
  //baseURL: '',
  // 时间短了 先关闭掉
  //timeout: 2000,
  // 是否是跨域请求
  withCredentials: true,
  headers: {'Content-Type': 'application/x-www-form-urlencoded', 'X-Requested-With': 'XMLHttpRequest'},
  // transformRequest: [function (data) {
  //   // 这里可以在发送请求之前对请求数据做处理，比如form-data格式化等，这里可以使用开头引入的Qs（这个模块在安装axios的时候就已经安装了，不需要另外安装）
  //   data = Qs.stringify(data);
  //   return data;
  // }],
  //返回数据类型
  responseType: 'json'
};
//那年乱世如麻，愿你们来世拥有锦绣年华.此生无悔入华夏，来世还在种花家
const AxiosInst = axios.create(config);
//请求拦截器
AxiosInst.interceptors.request.use((config) => {
  let token = window.sessionStorage.getItem('loginToken');
  if (token) {
    let info = window.sessionStorage.getItem('loginInfo');
    if (info !== null) {
      let userInfo = JSON.parse(info);
      let expireTime = parseInt(userInfo.expireTime);
      let nowTime = parseInt(new Date().getTime());
      if (nowTime > expireTime) {
        //清除临时的本地存储
        window.sessionStorage.removeItem('loginInfo');
        window.sessionStorage.removeItem('loginToken');
      } else {
        expireTime = nowTime + parseInt(window.expireTime);
        userInfo.expireTime = expireTime;
        window.sessionStorage.setItem('loginInfo', JSON.stringify(userInfo));
      }
    }
  }
  // if (config.method === 'post') {
  //如果是post方式，则使用json方式处理
  config.headers = {'Content-Type': 'application/json;charset=UTF-8', 'X-Requested-With': 'XMLHttpRequest', 'x-access-token': token};
  //config.headers = {'Content-Type': 'application/json;charset=UTF-8', 'X-Requested-With': 'XMLHttpRequest'};
  // }
  return config;
}, (err) => {
  return Promise.reject(err);
});
//响应拦截器
AxiosInst.interceptors.response.use(response => {
  //检查数据是否返回NULL
  let headers = response.headers;
  if (headers['zoom-auth']) {
    //app 调用踢出弹框
    let msg = decodeURIComponent(headers['zoom-auth']);
    //后台则使用全局弹框踢出登录
    if (window.Bus) {
      let val = {
        msg: msg
      };
      window.Bus.$emit('yolo_sys_out_emit', val);
    }
  }
  let allCookies = document.cookie;
  if (headers['auth-perms']) {
    console.log('auth-perms');
    console.log(allCookies);
    sessionStorage.setItem('authPerms', headers['auth-perms']);
  }
  if (headers['auth-token']) {
    console.log('auth-token');
    console.log(allCookies);
    sessionStorage.setItem('loginToken', headers['auth-token']);
  }

  //检查数据是否返回NULL
  if (response.data === null) {
    return Promise.reject(response);
  }
  return response;
}, (error) => {
  let headers = error.response.headers;
  if (headers['zoom-auth']) {
    let msg = decodeURIComponent(headers['zoom-auth']);
    //后台则使用全局弹框踢出登录
    if (window.Bus) {
      let val = {
        msg: msg
      };
      window.Bus.$emit('yolo_sys_out_emit', val);
    }
  }
  if (headers['auth-perms']) {
    sessionStorage.setItem('authPerms', headers['auth-perms']);
  }
  if (headers['auth-token']) {
    sessionStorage.setItem('loginToken', headers['auth-token']);
  }

  // 下面是接口回调的status ,因为我做了一些错误页面,所以都会指向对应的报错页面
  switch (error.response.status) {
    case 404:
      router.push({
        // path: '/404'
      });
      break;
    case 500:
      router.push({
        // path: '/500'
      });

      break;
    case 504:
      router.push({
        path: '/login'
      });
      break;
    case 666://未登录返回登录界面
      router.push({
        path: '/login'
      });
      break;
    case 604://未登录返回登录界面
      router.push({
        path: '/login'
      });
      break;
  }
  //请求错误时做些事
  return Promise.reject(error);
});
export default AxiosInst;
